package com.zjsru.plan2023.oneday;

/**
 * @Author: cookLee
 * @Date: 2023-11-20
 * 最大子数组和
 */
public class MaxSubArray {
    /**
     * 主要
     * \
     * 输入：nums = [-2,1,-3,4,-1,2,1,-5,4]
     * 输出：6
     * 解释：连续子数组 [4,-1,2,1] 的和最大，为 6 。
     * \
     * 输入：nums = [5,4,-1,7,8]
     * 输出：23
     * \
     * @param args args
     */
    public static void main(String[] args) {
        MaxSubArray maxSubArray = new MaxSubArray();
        int[] nums = new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4};
        System.out.println(maxSubArray.maxSubArray(nums));
    }

    /**
     * 最大子阵列:动态规划
     *
     * @param nums nums
     * @return int
     */
    public int maxSubArray(int[] nums) {
        int pre = 0;
        int ans = nums[0];
        for (int num : nums) {
            pre = Math.max(num, pre + num);
            ans = Math.max(ans, pre);
        }
        return ans;
    }

}
